package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.contast.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserManagerService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: UserManagerController
 * @Author: zhaopu
 * @Date: 2020/7/15 10:23
 * @Description:
 */
@RestController
@RequestMapping("/userManager")
public class UserManagerController {
    @Reference
    private UserManagerService userManagerService;

    //新增用户
    @RequestMapping("/add")
    public Result add(@RequestBody User user, Integer[] roleIds){
        try {
            userManagerService.add(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_USER_FAIL);
        }
        return new Result(true, MessageConstant.ADD_USER_SUCCESS);
    }

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userManagerService.queryPage(queryPageBean);
    }

    //删除用户
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            userManagerService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_USER_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
    }

    //根据id查询用户
    @RequestMapping("/findById")
    public Result findById(Integer id){

        try {
            User user = userManagerService.findById(id);

            return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }

    //根据用户id查询出角色id
    @RequestMapping("/findRoleIdByUserId")
    public Result findRoleIdByUserId(Integer id){
        try {
            List<Integer> roleIds = userManagerService.findRoleIdByUserId(id);
            return new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ROLE_FAIL);
        }
    }

    //更新用户
    @RequestMapping("/edit")
    public Result edit(@RequestBody User user, Integer[] roleIds){
        try {
            userManagerService.edit(user,roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
    }
}
